package com.project.demo.api;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.project.demo.game.MatchRequest;
import com.project.demo.game.MatchResponse;
import com.project.demo.game.Matcher;
import com.project.demo.game.OnlineUserManager;
import com.project.demo.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * Created with IntelliJ IDEA.
 * Description:通过这个类来处理匹配功能中的 websocket 请求
 * User:DELL
 * Time:11:55
 */
@Component
public class MatchAPI extends TextWebSocketHandler {
    private ObjectMapper objectMapper=new ObjectMapper();

    @Autowired
    private Matcher matcher;
    @Autowired
    private OnlineUserManager onlineUserManager;
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        //玩家上线，加入onlineUserManager中
        //获取当前用户的身份信息
        try {
            User user = (User) session.getAttributes().get("user");
            //判断当前用户是否已经登录过/处于在线状态
            WebSocketSession tmpSession = onlineUserManager.getFromGameHall(user.getUserId());
            if (tmpSession!=null){
                //当前用户已经登录过了，要告知客户端
                MatchResponse response = new MatchResponse();
                response.setOk(false);
                response.setReason("当前禁止多开！");
                session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
                session.close();
                return;
            }
            //设置上线状态
            onlineUserManager.enterGameHall(user.getUserId(), session);
            System.out.println("玩家 " + user.getUsername() + " 进入游戏大厅！");
        }catch (NullPointerException e){
            e.printStackTrace();
            //当前身份为空，用户未登录
            MatchResponse response = new MatchResponse();
            response.setOk(false);
            response.setReason("您尚未登录！不能进行后续匹配功能！");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        //实现开始匹配请求和停止匹配请求
        User user = (User) session.getAttributes().get("user");
        //获取客户端给服务器发送的数据
        String payload =message.getPayload();
        //JSON转为java
        MatchRequest request=objectMapper.readValue(payload, MatchRequest.class);
        MatchResponse response =new MatchResponse();
        if (request.getMessage().equals("startMatch")){
            //进入匹配队列
           matcher.add(user);
            //玩家信息放入匹配队列后，返回响应给客户端
            response.setOk(true);
            response.setMessage("startMatch");
        }else if(request.getMessage().equals("stopMatch")){
            //退出匹配队列
            matcher.remove(user);
            //返回响应给客户端
            response.setOk(true);
            response.setMessage("stopMatch");
        }else {
            //非法情况
            response.setOk(false);
            response.setReason("非法的匹配请求！");
        }
    }

    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
        //玩家下线,从onlineUserManager中删除
        //获取当前用户的身份信息
        try {
            User user = (User) session.getAttributes().get("user");
            WebSocketSession tmpSession = onlineUserManager.getFromGameHall(user.getUserId());
            if (tmpSession==session) {
                onlineUserManager.exitGameHall(user.getUserId());
            }
            //如果玩家正在匹配中，而连接断开了，则移除匹配队列
            matcher.remove(user);
        }catch (NullPointerException e){
            e.printStackTrace();
            //当前身份为空，用户未登录
            MatchResponse response = new MatchResponse();
            response.setOk(false);
            response.setReason("您尚未登录！不能进行后续匹配功能！");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
        }

    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        //玩家下线,从onlineUserManager中删除。
        //获取当前用户的身份信息
        try {
            User user = (User) session.getAttributes().get("user");
            WebSocketSession tmpSession = onlineUserManager.getFromGameHall(user.getUserId());
            if (tmpSession==session) {
                onlineUserManager.exitGameHall(user.getUserId());
            }
            //如果玩家正在匹配中，而连接断开了，则移除匹配队列。
            matcher.remove(user);
        }catch (NullPointerException e){
            e.printStackTrace();
            //当前身份为空，用户未登录。
            MatchResponse response = new MatchResponse();
            response.setOk(false);
            response.setReason("您尚未登录！不能进行后续匹配功能！");
            session.sendMessage(new TextMessage(objectMapper.writeValueAsString(response)));
        }
    }
}
